﻿using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.Resources;
using Globsite.Globalization.Mvc.DbResources.Repositories;

namespace Globsite.Globalization.Mvc.DbResources
{
    public class DbResourceReader : IResourceReader
    {
        private readonly string baseName;
        private readonly CultureInfo cultureInfo;
        private IDictionary<string, string> resources;
        private readonly object resourcesSyncLock;

        private RepositoryBase resourceRepositoryField;
        private RepositoryBase resourceRepository
        {
            get { return this.resourceRepositoryField ?? (this.resourceRepositoryField = (new RepositoryFactory()).CreateRepository()); }
        }

        public DbResourceReader(string baseName, CultureInfo cultureInfo)
        {
            Debug.WriteLine(string.Format("DbResourceReader.DbResourceReader({0}, {1})", baseName, cultureInfo));

            this.resourcesSyncLock = new object();
            this.baseName = baseName;
            this.cultureInfo = cultureInfo;
        }

        #region IResourceReader Members

        public IDictionaryEnumerator GetEnumerator()
        {
            Debug.WriteLine("DbResourceReader.GetEnumerator()");

            if (this.resources == null)
                lock (this.resourcesSyncLock)
                    if (this.resources == null)
                        this.resources = this.resourceRepository.GetResources(this.baseName, this.cultureInfo.Name);

            var enumerator = ((IDictionary)this.resources).GetEnumerator();

            return enumerator;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            Debug.WriteLine("DbResourceReader.IEnumerable.GetEnumerator()");

            return GetEnumerator();
        }

        public void Close()
        {
            Debug.WriteLine("DbResourceReader.Close()");

            Dispose();
        }

        public void Dispose()
        {
            Debug.WriteLine("DbResourceReader.Dispose()");

            this.resources = null;
        }

        #endregion
    }
}
